package cn.virens.main.cmpt;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.virens.main.AppConfig;

public class ComponentRegistry implements Component {
	private static final Logger logger = LoggerFactory.getLogger(ComponentRegistry.class);

	private final List<Component> components = new ArrayList<>();

	/**
	 * 插件 生命周期管理
	 * 
	 * @param  component 自定义组件
	 * @return
	 */
	public <T extends Component> T register(T component) {
		return components.add(component) ? component : null;
	}

	@Override
	public void initialize(AppConfig config) throws Exception {
		logger.debug("Load Components...");

		for (Component component : components) {
			logger.debug("Load Component {} initialize...", component.name());

			try {
				component.initialize(config);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}

		logger.debug("Loaded Components:" + components.size());
	}

	@Override
	public void destroy() throws Exception {
		logger.debug("Stop Components...");

		for (Component component : components) {
			logger.debug("Stop Component {} stop...", component.name());

			try {
				component.destroy();
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}

		logger.debug("Stoped Components:" + components.size());
	}

}
